package com.example.practice;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * 模拟登陆成功后的主界面,这里只提供强制下线功能
 */
public class MainActivity extends AppCompatActivity {

    private ForceOfflineReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button forceOffline = findViewById(R.id.force_offline);
        forceOffline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.practice.FORCE_OFFLINE");
                sendBroadcast(intent); // 发送广播,用于强制下线,其中强制下线的代码写在广播中,这样的话强制下线不会依附于 任何界面
            }
        });
    }

    /**
     * 注册广播接收器
     */
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.practice.FORCE_OFFLINE");
        receiver = new ForceOfflineReceiver();
        registerReceiver(receiver, intentFilter);
    }

    //为什么这里的注册广播和销毁广播写在onPause()和onResume()方法中呢？
    // 这是因为我们需要保证只有处于栈顶的Acitvity才能接收到这条广播，非栈顶的活动没必要接受这条广播，
    // 所以写在onPause()和onResume()中可以很好的解决这个问题。
    /**
     * 销毁广播接收器
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (receiver!=null){
            unregisterReceiver(receiver);
            receiver =null;
        }
    }

    /**
     * 强制下线的广播接收器
     */
    class ForceOfflineReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Warning");
            builder.setMessage("You are forced to be offline. Please try to login again.");
            builder.setCancelable(false); // 设置弹窗不可取消
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityController.finishAll(); // 销毁所有活动
                    Intent i = new Intent(context, LoginActivity.class);
                    context.startActivity(i); // 重启LoginActivity
                }
            });
            builder.show();
        }
    }
}